<template>
  <el-select
    v-model="value"
    filterable
    remote
    reserve-keyword
    :remote-method="supplierMethod"
    :loading="optionLoading"
    clearable
    @change="change"
  >
    <el-option
      v-for="item in supplierOptions"
      :key="item.value"
      :label="item.supplier_name"
      :value="item.s_id"
    ></el-option>
  </el-select>
</template>
<script setup>
import { getSupplierList } from "./api.js";

const props = defineProps({
  modelValue: [String, Number, Array],
});

const value = computed(() => {
  return props.modelValue;
});

const supplierOptions = ref([]);
const optionLoading = ref(false);
const supplierMethod = async (query) => {
  if (query) {
    const { data } = await getSupplierList({
      page: 1,
      page_size: 1000,
      supplier_name: query,
    });
    supplierOptions.value = data || [];
  } else {
    supplierOptions.value = [];
  }
};

const emit = defineEmits(["update:modelValue"]);
const change = (val) => {
  const item = supplierOptions.value.find((i) => i.s_id == val);
  emit("change", item?.label || "");
  emit("changeItem", item || "");
  emit("update:modelValue", val);
};

defineExpose({ supplierMethod });
</script>
